package com.vf.cloud.paas.app.master.api.asset.service.impl;

import java.util.List;
import org.springframework.stereotype.Service;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.vf.cloud.paas.app.master.api.asset.service.IAssetClassify;
import com.vf.cloud.paas.app.master.common.domain.Asset;
import com.vf.cloud.paas.app.master.common.domain.AssetClassify;

@Service
public class AssetClassifyImpl implements IAssetClassify {

	public List<AssetClassify> getChildrens(AssetClassify param) {
		if(!StrKit.isBlank(param.getName())) {
			String sql = "SELECT T.*, (CASE  WHEN (SELECT COUNT(ID) AS COUNT FROM "+AssetClassify.TABLE_NAME+" WHERE PID=T.ID)>0 THEN TRUE ELSE  FALSE END ) AS leaf  FROM "+AssetClassify.TABLE_NAME+"  T WHERE T.PID=?  and t.name like '%"+param.getName()+"%'   ORDER BY T.SORT ASC";
			return AssetClassify.dao.find(sql, param.getId());
		}else {
			String sql = "SELECT T.*, (CASE  WHEN (SELECT COUNT(ID) AS COUNT FROM "+AssetClassify.TABLE_NAME+" WHERE PID=T.ID)>0 THEN TRUE ELSE  FALSE END ) AS leaf  FROM "+AssetClassify.TABLE_NAME+"  T WHERE T.PID=?    ORDER BY T.SORT ASC";
			return AssetClassify.dao.find(sql, param.getId());
		}
	}
	
	public List<AssetClassify> getChildren(AssetClassify param) {
		String _sql = "select * from MASTER_ASSET_CLASSIFY where pid=? ";
		if(!StrKit.isBlank(param.getName())) {
			_sql+=" and name like '%"+param.getName()+"%'";
		}
		_sql+=" order by sort asc ";
		
		List<AssetClassify> list=AssetClassify.dao.find(_sql, param.getId());
		for(AssetClassify a:list) {
			param.setId(a.getId());
			a.setChildren(getNextChildren(param));;
		}
		return list;
	}

	public List<AssetClassify> getNextChildren(AssetClassify param) {
		String _sql = "select * from MASTER_ASSET_CLASSIFY where pid=? ";
		if(!StrKit.isBlank(param.getName())) {
			_sql+=" and name like '%"+param.getName()+"%'";
		}
		_sql+=" order by sort asc ";
		return AssetClassify.dao.find(_sql, param.getId());
	}



	@Override
	public void delete(String id) {
		 deleteChildrens(id);
	}

	public void deleteChildrens(String id) {
		List<AssetClassify> assetClassifys = AssetClassify.dao.find("select id from "+AssetClassify.TABLE_NAME+" where pid=? ",id);
		for (AssetClassify classify : assetClassifys) {
			if(classify.delete()) {
				deleteChildrens(classify.getId());
				Db.delete("delete From "+Asset.TABLE_NAME+" where classify_id=? ",classify.getId());
			}
		}
		Db.delete("delete From "+Asset.TABLE_NAME+" where classify_id=? ",id);
		AssetClassify.dao.deleteById(id);
	}

}
